package com.example.common.inteceptor;

import com.example.common.utils.JwtUtils;
import io.jsonwebtoken.JwtException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        token = token.replace("Bearer ", "");
        if (validateToken(token)) {
            // 将用户信息存入安全上下文等操作
            return true;
        } else {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid Token");
            return false;
        }
    }

    private boolean validateToken(String token) {
        try {
            JwtUtils.parseToken(token);
            return true;
        } catch (JwtException e) {
            return false;
        }
    }
}
   